/*
 * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.beiuu.myfirstandroidapp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.beiuu.myfirstandroidapp.Bean.Fruit;
import com.beiuu.myfirstandroidapp.Bean.News;
import com.beiuu.myfirstandroidapp.Bean.NewsAdapter;
import com.beiuu.myfirstandroidapp.Refresh.HeaderAndFooterWrapper;
import com.beiuu.myfirstandroidapp.Refresh.MessageRelativeLayout;
import com.beiuu.myfirstandroidapp.Refresh.PullRefreshRecyclerView;
import com.beiuu.myfirstandroidapp.Tools.RandomValue;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static java.lang.Thread.sleep;


public class RecyclerPullActivity extends AppCompatActivity {

    private List<Fruit> fruitlist = new ArrayList<Fruit>();
    private List<News> newslist = new ArrayList<News>();
    private PullRefreshRecyclerView rv;
    private Context context;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Gson gson = new Gson();
            String string_json = (String) msg.obj;

            JsonParser parser = new JsonParser();
            JsonArray jsonArray = parser.parse(string_json).getAsJsonArray();

            for (JsonElement one : jsonArray) {

                //使用GSON，直接转成Bean对象
                News news = gson.fromJson(one, News.class);
                newslist.add(news);
            }

            NewsAdapter Na = new NewsAdapter(context,newslist);
            rv.setAdapter(Na);

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_pull);

        context = this ;
        //测试数据
        //initFruit();
        initNews();


        rv = (PullRefreshRecyclerView) findViewById(R.id.recyc1);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        //切换横屏滚动
        //lm.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv.setLayoutManager(lm);

        //FruitAdapter fa = new FruitAdapter(fruitlist);
        NewsAdapter Na = new NewsAdapter(this,newslist);

        HeaderAndFooterWrapper ss = new HeaderAndFooterWrapper(Na);
        //系统自定义分割线
//        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
//        rv.addItemDecoration(decoration);
        //自定义分割线类
        //rv.addItemDecoration(new NewsDecoration(this));
        rv.setAdapter(ss);

        rv.setOnRefreshListener(new PullRefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {

                initNews();

                NewsAdapter Na = new NewsAdapter(context,newslist);
                rv.setAdapter(new HeaderAndFooterWrapper(Na));

                rv.stopRefresh();
            }

            @Override
            public void onLoadMore() {
                rv.stopLoadMore();
            }
        });

        //加载接口数据
        //getDatasync("http://junipero.cn/index/Index/dysfz");

    }

    private void initFruit(){

        for (int i=0;i<20;i++){
            Fruit f = new Fruit("test"+i , R.drawable.man);
            fruitlist.add(f);
        }

    }

    private void initNews(){

        List<News> temp = new ArrayList<News>();
        for (int i=0;i<5;i++){
            News f = new News();
            f.setTitle(RandomValue.getLongString());
            f.setImage("http://p1.pstatp.com/origin/6ecb000bd1d1f43912a3");
            f.setUrl("url"+i);
            temp.add(f);
        }
        temp.addAll(newslist);
        newslist = temp;

        try {
            sleep(1500); //暂停，每一秒输出一次
        }catch (InterruptedException e) {

        }
    }

    public void getDatasync(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                    Request request = new Request.Builder()
                            .url(url)//请求接口。如果需要传参拼接到接口后面。
                            .build();//创建Request 对象
                    Response response = null;
                    response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
//                        Log.d("kwwl","response.code()=="+response.code());
//                        Log.d("kwwl","response.message()=="+response.message());

                        Message mag = handler.obtainMessage();
                        mag.obj = response.body().string();
                        handler.sendMessage(mag);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
/*
    TODO: 1.利用测试数据铺满整个RecycleView   - 完成
    TODO: 2.读取接口数据铺满整个RecycleView   - 完成
    TODO: 3.利用 Picasso 加载接口中的图片     - 完成 180322
    TODO: 4.修正布局和样式                   - 完成 180323
    TODO: 5.实现下拉刷新和上拉加载             https://blog.csdn.net/q714093365/article/details/77063084
    TODO: 6.点击事件跳转到 WebView           - 完成 180323
    TODO: 7.show页面的顶部返回栏（下滑隐藏，上滑显示）
    TODO: 8.index页面的顶部新闻栏目滚动条
 */
